<template>
  <div class="merchant-home">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover" v-loading="loading">
          <div slot="header">
            <span>今日订单</span>
          </div>
          <div class="card-content">
            <span class="number">{{ dashboardData.todayOrderCount || 0 }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" v-loading="loading">
          <div slot="header">
            <span>商品总数</span>
          </div>
          <div class="card-content">
            <span class="number">{{ dashboardData.productCount || 0 }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" v-loading="loading">
          <div slot="header">
            <span>今日收入</span>
          </div>
          <div class="card-content">
            <span class="number">¥{{ dashboardData.todayRevenue ? Number(dashboardData.todayRevenue).toFixed(2) : '0.00' }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单趋势图 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card shadow="hover" v-loading="loading">
          <div slot="header">
            <span>近7日订单趋势</span>
          </div>
          <div id="order-trend-chart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近订单 -->
    <div class="recent-orders">
      <h3>最近订单</h3>
      <el-table
        v-loading="loading"
        :data="dashboardData.recentOrders || []"
        style="width: 100%"
        border
      >
        <el-table-column label="订单编号" width="180">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewOrder(scope.row.id)">{{ scope.row.orderNumber }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="recipientName" label="收件人" width="120"></el-table-column>
        <el-table-column prop="recipientPhone" label="联系电话" width="140"></el-table-column>
        <el-table-column prop="payAmount" label="支付金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.payAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">{{ getOrderStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewOrder(scope.row.id)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              type="text" 
              size="small" 
              @click="acceptOrder(scope.row.id)">接单</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getMerchantDashboardData } from '@/api/merchant';
import * as echarts from 'echarts';

export default {
  name: 'MerchantHome',
  data() {
    return {
      loading: false,
      dashboardData: {
        todayOrderCount: 0,
        productCount: 0,
        todayRevenue: 0,
        recentOrders: [],
        statusCounts: {},
        orderTrend: []
      },
      trendChart: null
    }
  },
  computed: {
    merchantId() {
      return this.$store.state.userInfo && this.$store.state.userInfo.id ? this.$store.state.userInfo.id : null;
    }
  },
  mounted() {
    if (this.merchantId) {
      this.fetchDashboardData();
    } else {
      this.$message.error('未获取到商家ID，请重新登录');
    }
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.trendChart) {
      this.trendChart.dispose();
      this.trendChart = null;
    }
    
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    fetchDashboardData() {
      this.loading = true;
      
      getMerchantDashboardData(this.merchantId)
        .then(res => {
          if (res.code === 200) {
            this.dashboardData = res.data;
            
            this.$nextTick(() => {
              this.initOrderTrendChart();
            });
          } else {
            this.$message.error(res.message || '获取仪表盘数据失败');
          }
        })
        .catch(err => {
          console.error('获取仪表盘数据失败', err);
          this.$message.error('获取仪表盘数据失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    initOrderTrendChart() {
      // 初始化图表
      if (!this.trendChart) {
        this.trendChart = echarts.init(document.getElementById('order-trend-chart'));
      }
      
      // 图表数据
      const trendData = this.dashboardData.orderTrend || [];
      const dates = trendData.map(item => item.date);
      const counts = trendData.map(item => item.count);
      const amounts = trendData.map(item => item.amount);
      
      // 图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['订单数量', '订单金额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: [
          {
            type: 'value',
            name: '订单数量',
            position: 'left',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#5470C6'
              }
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '订单金额',
            position: 'right',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#91CC75'
              }
            },
            axisLabel: {
              formatter: '¥{value}'
            }
          }
        ],
        series: [
          {
            name: '订单数量',
            type: 'bar',
            data: counts
          },
          {
            name: '订单金额',
            type: 'line',
            yAxisIndex: 1,
            data: amounts,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#91CC75'
            },
            lineStyle: {
              width: 3
            }
          }
        ]
      };
      
      // 设置图表配置
      this.trendChart.setOption(option);
    },
    
    handleResize() {
      if (this.trendChart) {
        this.trendChart.resize();
      }
    },
    
    getOrderStatusText(status) {
      const statusMap = {
        0: '已取消',
        1: '待接单',
        2: '待配送',
        3: '配送中',
        4: '已完成'
      };
      return statusMap[status] || '未知状态';
    },
    
    getOrderStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'success'
      };
      return typeMap[status] || '';
    },
    
    viewOrder(orderId) {
      this.$router.push(`/merchant/order?id=${orderId}`);
    },
    
    acceptOrder(orderId) {
      this.$confirm('确认接受此订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 接单处理逻辑，后续实现
        // 模拟API调用，实际项目中应调用接单API
        this.$message({
          type: 'success',
          message: `订单 ${orderId} 接单成功`
        });
        this.fetchDashboardData(); // 刷新数据
      }).catch(() => {});
    }
  }
}
</script>

<style scoped>
.merchant-home {
  padding: 20px;
}
.card-content {
  text-align: center;
}
.number {
  font-size: 24px;
  font-weight: bold;
}
.chart-container {
  height: 300px;
  width: 100%;
}
.recent-orders {
  margin-top: 30px;
}
</style> 